<script setup lang="ts">
import { useI18n } from "vue-i18n";
import { useRouter } from "vue-router";
import { message } from "@/utils/message";
import { loginRules } from "./utils/rule";
// import { useNav } from "@/layout/hooks/useNav";
import type { FormInstance } from "element-plus";
import { $t, transformI18n } from "@/plugins/i18n";
import { useLayout } from "@/layout/hooks/useLayout";
import { logo } from "./utils/static";
import { useRenderIcon } from "@/components/reIcon/src/hooks";
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useTranslationLang } from "@/layout/hooks/useTranslationLang";
import { useDataThemeChange } from "@/layout/hooks/useDataThemeChange";
import Lock from "@iconify-icons/ri/lock-fill";
import User from "@iconify-icons/ri/user-3-fill";
import { setToken } from "@/utils/auth";
import { addPathMatch } from "@/router/utils";
import { usePermissionStoreHook } from "@/store/modules/permission";

defineOptions({
  name: "Login"
});
const router = useRouter();
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const { initStorage } = useLayout();
initStorage();

const { t } = useI18n();
const { dataThemeChange } = useDataThemeChange();
dataThemeChange();
// const { title, getDropdownItemStyle, getDropdownItemClass } = useNav();
const { translationCh, translationEn } = useTranslationLang();

const ruleForm = reactive({
  username: "test",
  password: "admin123",
  fab: "FAB1",
  language: "English"
});

const onLogin = async (formEl: FormInstance | undefined) => {
  loading.value = true;
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 全部采取静态路由模式
      usePermissionStoreHook().handleWholeMenus([]);
      addPathMatch();
      setToken({
        username: "admin",
        roles: ["admin"],
        accessToken: "eyJhbGciOiJIUzUxMiJ9.admin"
      } as any);
      router.push("/");
      message("登录成功", { type: "success" });
    } else {
      loading.value = false;
      return fields;
    }
  });
};

const onChangeLanguage = (value: string) => {
  value === "English" ? translationEn : translationCh;
};

/** 使用公共函数，避免`removeEventListener`失效 */
function onkeypress({ code }: KeyboardEvent) {
  if (code === "Enter") {
    onLogin(ruleFormRef.value);
  }
}

onMounted(() => {
  window.document.addEventListener("keypress", onkeypress);
});

onBeforeUnmount(() => {
  window.document.removeEventListener("keypress", onkeypress);
});
</script>
<template>
  <div class="login-bg">
    <div class="login-header">
      <div>
        <img :src="logo" class="logo" />
      </div>
      <div class="item-span margin-left-20">
        <span>Profile: </span>
        <span>PROD</span>
      </div>
      <div class="item-span margin-left-20">
        <span>Version: </span>
        <span>v2.23.2</span>
      </div>
    </div>
    <div class="login-content">
      <div class="login-box">
        <div class="login-form">
          <el-form
            autocomplete="off"
            ref="ruleFormRef"
            :model="ruleForm"
            :rules="loginRules"
            size="large"
          >
            <el-form-item
              autocomplete="off"
              :rules="[
                {
                  required: true,
                  message: transformI18n($t('usernameReg')),
                  trigger: 'blur'
                }
              ]"
              prop="username"
            >
              <el-input
                class="login-item-input"
                autocomplete="off"
                clearable
                v-model="ruleForm.username"
                :placeholder="t('username')"
                :prefix-icon="useRenderIcon(User)"
              />
            </el-form-item>

            <el-form-item prop="password">
              <el-input
                type="password"
                class="login-item-input"
                auto-complete="new-password"
                clearable
                show-password
                v-model="ruleForm.password"
                :placeholder="t('password')"
                :prefix-icon="useRenderIcon(Lock)"
              />
            </el-form-item>
            <div class="form-item-box">
              <el-form-item label="FAB:">
                <el-select v-model="ruleForm.fab" class="item-input">
                  <el-option label="FAB1" value="FAB1" />
                  <el-option label="FAB2" value="FAB2" />
                </el-select>
              </el-form-item>

              <el-form-item label="Language:">
                <el-select
                  v-model="ruleForm.language"
                  class="item-input"
                  @change="onChangeLanguage(ruleForm.language)"
                >
                  <el-option label="English" value="English" />
                  <el-option label="Chinese" value="Chinese" />
                </el-select>
              </el-form-item>
            </div>
            <el-button
              class="w-full mt-4 login-button"
              size="default"
              type="primary"
              :loading="loading"
              @click="onLogin(ruleFormRef)"
            >
              {{ t("hslogin") }}
            </el-button>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
@import url("@/style/login.css");
</style>

<style lang="scss" scoped>
:deep(.el-input-group__append, .el-input-group__prepend) {
  padding: 0;
}

.translation {
  ::v-deep(.el-dropdown-menu__item) {
    padding: 5px 40px;
  }

  .check-zh {
    position: absolute;
    left: 20px;
  }

  .check-en {
    position: absolute;
    left: 20px;
  }
}
</style>
